<template>
  <el-drawer
    :title="row.id ? '编辑' :'新增'"
    :visible.sync="visibleDrawer"
    :wrapper-closable="false"
    :before-close="handleClose"
    direction="rtl"
    size="600px"
    @opened="handleOpen"
  >
    <div style="padding: 5px">
      <el-form ref="rowForm" :model="row" :rules="rules">
        <el-form-item prop="name">
          <el-input
            v-model="row.name"
            autocomplete="off"
            :autofocus="true"
            :focus="true"
            show-word-limit
            maxlength="20"
            placeholder="请输入角色名"
          />
        </el-form-item>
        <el-form-item prop="remark">
          <el-input
            v-model="row.remark"
            autocomplete="off"
            type="textarea"
            :rows="3"
            placeholder="备注"
            show-word-limit
            maxlength="200"
          />
        </el-form-item>
      </el-form>
      <el-tree
        ref="tree"
        :data="tree"
        show-checkbox
        default-expand-all
        node-key="code"
        highlight-current
        :props="props"
        @check-change="handleChange"
      />
      <div class="text-center">
        <el-button @click="visibleDrawer = false">取 消</el-button>
        <el-button type="primary" :loading="btnSaveLoading" @click="handleSave(true)">保存并新增</el-button>
        <el-button type="primary" :loading="btnSaveLoading" @click="handleSave(false)">保 存</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import Role from '@/api/entity/Role'
import RoleService from '@/api/RoleService'

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    row: {
      type: Role,
      required: true
    }
  },
  data() {
    return {
      btnSaveLoading: false,
      tree: null,
      props: Object.freeze({
        label: 'name',
        children: 'nodes'
      }),
      selectedCodes: new Set(),
      rules: Object.freeze({
        name: [
          {required: true, message: '请输入角色名', trigger: 'blur'},
          {min: 1, max: 20, message: '长度必须在 1-20 个字符', trigger: 'blur'}
        ]
      })
    }
  },
  computed: {
    visibleDrawer: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  created() {
    RoleService.getAuthorityTree().then(result => {
      result
        .ifToastErrorMessage('权限树加载失败')
        .ifSuccess(() => {
          this.tree = result.data
        })
    })
  },
  methods: {
    handleOpen() {
      if (this.row.authorities) { // 编辑时填充权限树
        const refTree = this.$refs.tree
        // 过滤:只选择叶子节点, 父节点会自动选中
        const keys = this.row.authorities.filter(code => {
          return refTree.getNode(code)?.isLeaf
        })
        refTree.setCheckedKeys(keys)
      }
    },
    /**
     *
     * @param row {Authority}
     * @param currentChecked {boolean}
     * @param childChecked {boolean}
     */
    handleChange(row, currentChecked, childChecked) {
      row.checked = currentChecked || childChecked
      if (!row.nodes) {
        if (currentChecked) {
          this.selectedCodes.add(row.code)
        } else {
          this.selectedCodes.delete(row.code)
        }
      }
    },
    handleClose() {
      this.$refs.rowForm.resetFields()
      this.$refs.tree.setCheckedKeys([])
      this.visibleDrawer = false
    },
    /**
     *
     * @param saveAndNew {boolean} true：保存并新增 ； false：保存
     * @returns {Promise<void>}
     */
    async handleSave(saveAndNew) {
      if (this.selectedCodes.size === 0) {
        this.$message.warning('请选择权限')
        return
      }
      console.log(['role', this.row])
      const valid = await this.$refs.rowForm.validate()
      if (!valid) {
        return
      }
      this.btnSaveLoading = true
      this.row.authorityTree = this.tree
      const result = await (this.row.id ? RoleService.update(this.row) : RoleService.save(this.row)).finally(() => (this.btnSaveLoading = false))
      result
        .ifToastMessage('保存成功', '保存失败')
        .ifSuccess(() => {
          this.$emit('ok')
          if (saveAndNew) { // 清理不需要保留的值
            this.row.id = null
            this.row.name = null
          } else {
            this.handleClose()
          }
        })
    }
  }
}
</script>
